package com.example.controller;

import com.example.model.SimpleCounter;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@Controller
public class BaseController {
	private static final SimpleCounter sc = new SimpleCounter();

	private static final String VIEW_INDEX = "home";
	private final static org.slf4j.Logger logger = LoggerFactory.getLogger(BaseController.class);

	private static synchronized long getNextCounterValue() {
		sc.increase();
		return sc.getValue();
	}

	@RequestMapping("/love")
	public String love(HttpServletRequest request){
		long counterValue = BaseController.getNextCounterValue();
		String equipmentString=getDeviceInfo(request);
		logger.debug("test : {}","通过这里");
		logger.debug("counter : {}",counterValue);
		logger.debug("equipment : {}", equipmentString);
		return "love";
	}

	@RequestMapping("/{name}")
	public String welcomeName(@PathVariable String name, Model model,HttpServletRequest request) {
		long counterValue = BaseController.getNextCounterValue();

		String equipmentString=getDeviceInfo(request);
		logger.debug("test : {}","通过这里");
		logger.debug("equipment : {}", equipmentString);
		model.addAttribute("message", "Welcome " + name);
		model.addAttribute("counter", counterValue);
		model.addAttribute("test","姐姐最美！！！");
		model.addAttribute("equipment",equipmentString);
		logger.debug("[welcomeName] counter : {}", counterValue);
		return VIEW_INDEX;
	}

	/**
	 * 获取请求设备信息
	 * @author 邹华桥
	 * @date 2020/8/11 14:19
	 * @param request 请求
	 * @return String 设备信息 pc端还是手机端
	 **/
	private static String getDeviceInfo(HttpServletRequest request) {
		///定义正则
		String pattern = "^Mozilla/\\d\\.\\d\\s+\\(+.+?\\)";
		String pattern2 = "\\(+.+?\\)";
		///将给定的正则表达式编译到模式中
		Pattern r = Pattern.compile(pattern);
		Pattern r2 = Pattern.compile(pattern2);

		String userAgent = request.getHeader("User-Agent");
		///创建匹配给定输入与此模式的匹配器
		Matcher m = r.matcher(userAgent);
		String result = null;
		if (m.find()) {
			result = m.group(0);
		}
		if(result == null){
			return null;
		}
		Matcher m2 = r2.matcher(result);
		if (m2.find()) {
			result = m2.group(0);
		}
		result = result.replace("(", "");
		result = result.replace(")", "");

		result = result.replace(" U;", "");
		result = result.replace(" zh-cn;", "");

		String android = "Android";
		String iPhone = "iPhone";
		String iPad = "iPad";
		if(result.contains(android) || result.contains(iPhone) || result.contains(iPad)){
			return "移动端";
		}else{
			return "PC端";
		}
	}

}
